package com.lyq.org.service.impl;

import com.lyq.basic.service.impl.BaseServiceImpl;
import com.lyq.org.domain.Department;
import com.lyq.org.mapper.DepartmentMapper;
import com.lyq.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author:liangyunqian
 * @Date: 2022/12/8  13:21
 * @Description:
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void insert(Department department) {
        //处理创建时间
        department.setCreate_time(new Date());
        departmentMapper.insert(department);
        //经过分析path = 父部门的path + 自己的id
        //处理path
        Department parent = department.getParent();
        String path = "";
        if(Objects.isNull(parent) || Objects.isNull(parent.getId())){
            path = "/"+department.getId();
        }else {
            parent = departmentMapper.getById(parent.getId());
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);

    }


    @Transactional
    @Override
    public void update(Department department) {
        //处理修改时间
        department.setUpdate_time(new Date());
        //处理path
        departmentMapper.update(department);
        Department parent = department.getParent();
        String path = "";
        if(Objects.isNull(parent) || Objects.isNull(parent.getId())){
            path = "/"+department.getId();
        }else {
            parent = departmentMapper.getById(parent.getId());
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }




    @Override
    public List<Department> tree() {
        return departmentMapper.tree();
    }

    @Override
    public List<Department> ctree() {
        return departmentMapper.ctree();
    }
}
